package com.yuchen.utils.springmvc;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * spring mvc  请求request时，对Date，Timestamp转义，对xss进行过滤
 */
public class BindingInitializer  implements WebBindingInitializer {

    private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private Validator validator;

	public void initBinder(WebDataBinder binder, WebRequest request) {		
        dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Timestamp.class, new CustomDateEditor(timestampFormat, true));
		binder.registerCustomEditor(String.class, new XssEditorSupport());
        if (this.validator != null && binder.getTarget() != null &&
                this.validator.supports(binder.getTarget().getClass())) {
            binder.setValidator(this.validator);
        }
	}

    public final void setValidator(Validator validator) {
        this.validator = validator;
    }

}

